import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/phoenix/api/revision_main_api.dart';
import 'package:dk_flutter_module_sale/phoenix/main_tabbar/main_tabbar_page.dart';
import 'package:dk_flutter_module_sale/phoenix/message/first_message/bean/bean_message.dart';
import 'package:dk_flutter_module_sale/phoenix/message/first_message/widget/widget_message_cell.dart';

class MainMessagePage extends CommonPage {
  final EventBus clickTabBarEventBus;
  MainMessagePage({this.clickTabBarEventBus}) : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    pageBloc.pageHttpGet(
        path: RevisionMainApi.firstMessageListUrl,
        widgetBuilderByData: (dynamic data) {
          //DataListBean
          List<DataListBean> list = (data as List != null)
              ? (data as List).map((item){
            DataListBean bean = DataListBean.fromJson(item);
            return bean;
          }).toList()
              :null;
          return MessageWidget(pageBloc,list,clickTabBarEventBus: this.clickTabBarEventBus,);
        }
    );
  }
}

class MessageWidget extends StatefulWidget {
  final EventBus clickTabBarEventBus;
  final CommonPageBloc pageBloc;
  final List<DataListBean> list;
  MessageWidget(this.pageBloc,this.list,{this.clickTabBarEventBus});

  @override
  MessageState createState() {
    return MessageState(this.pageBloc,this.list,clickTabBarEventBus: this.clickTabBarEventBus);
  }
}

class MessageState extends State<MessageWidget> with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin {
  List<DataListBean> list;
  CommonPageBloc messageBloc;
  final EventBus clickTabBarEventBus;
  DkEasyRefreshController easyRefreshController;
  MessageState(this.messageBloc,this.list,{this.clickTabBarEventBus});
  @override
  void initState() {
    super.initState();
    //打点消息页面
    UserTrack.trackViewScreen("公共消息-新", null);
    easyRefreshController = DkEasyRefreshController();
    FlutterBoost.singleton.addBoostContainerLifeCycleObserver((
        ContainerLifeCycle state, BoostContainerSettings settings) {
      if(settings.name != CommonWidgetRoute.COMMON_REVISION_HOME) {
        return;
      }
      if(state == ContainerLifeCycle.Appear) {
        refreshPage();
      } else if(state == ContainerLifeCycle.Destroy) {
        FlutterBoost.singleton.observersHolder.removeObserver(this);
      }
    });
    this.clickTabBarEventBus.on<ClickTabBarEvent>().listen((ClickTabBarEvent event){
      if(event.clickPage == TabBarPage.TabBarPageMessage){
        refreshPage();
      }
    });
  }

  Future<void> refreshPage() async{
    this.widget.pageBloc.dataHttpGet(
        showLoading: false,
        path: RevisionMainApi.firstMessageListUrl,
        handleErrorCode: (dynamic data1){
          easyRefreshController.finishRefresh(success: false);
        },
        handleFailResult: (dynamic data1,dynamic data2){
          easyRefreshController.finishRefresh(success: false);
        },
        handleResult: (dynamic data) {
          setState(() {
            //DataListBean
            list = (data as List != null)
                ? (data as List).map((item){
              DataListBean bean = DataListBean.fromJson(item);
              return bean;
            }).toList()
                :null;
            easyRefreshController.finishRefresh(success: true);
          });
        }
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(DKAppBarParams.noBackNoMenu(titleContent: "消息"),
      ),
      body:buildListWidget(context),
    );
  }

  Widget buildListWidget(BuildContext context) {
    return Container(
      color: Colors.white,
      child: DkRefreshListWidget.custom(
        controller: easyRefreshController,
          emptyWidget: list.length == 0 ? LogicPage(
              PortalConfig.smallEmptyPageParam) : null,
          onRefresh: this.refreshPage,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                  DataListBean bean = list[index];
                  return Container(
                    child: MessageCellWidget(
                      index: index, dataListBean: bean, tapCallback: () {
                      this.intoSubMessageTrack(bean);
                      RouteUtil.goPage(bean.appRouteUrl,
                          widgetContext: this.context,
                          widgetResultCallback: (map) {
                            refreshPage();
                          }
                      );
                    },),
                  );
                },
                childCount: list.length,
              ),
            ),
          ]
      ),
    );
  }

  void intoSubMessageTrack(DataListBean bean) {
    Map<String,dynamic> map = Map<String,dynamic>();
    map["name"] = bean.title;
    UserTrack.track("click_message_item", map);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
